<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="120px"
    >
      <el-form-item label="订单状态" prop="status">
        <el-radio-group v-model="queryParams.status" @input="handleQuery">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button
            v-for="dict in dict.type.order_status"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="关键字" prop="searchValue">
        <el-input
          v-model="queryParams.searchValue"
          placeholder="请输入关键字进行搜索"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单类型" prop="orderSource">
        <el-select
          v-model="queryParams.orderSource"
          placeholder="请选择订单类型"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.order_source"
            :key="dict.value"
            :value="dict.value"
            :label="dict.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="处方类型" prop="prescriptionType">
        <el-select
          v-model="queryParams.prescriptionType"
          placeholder="请选择处方类型"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.tcm_prescript_type"
            :key="dict.value"
            :value="dict.value"
            :label="dict.label">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="取药状态" prop="medicationStatus">
        <el-select
          v-model="queryParams.medicationStatus"
          placeholder="请选择取药状态"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.medication_status"
            :key="dict.value"
            :value="dict.value"
            :label="dict.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="申请人所属机构" prop="companyId">
        <SelectCompany
          :defaultValue.sync="queryParams.companyId"
          :isAll="true"
          :companyType="0"
          placeholder="请选择申请机构"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务所属机构" prop="checkAgency">
        <SelectCompany
          :defaultValue.sync="queryParams.checkAgency"
          :isAll="true"
          placeholder="请选择服务所属机构"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单归属渠道" prop="channelId">
        <Treeselect
          ref="Treeselect"
          style="width: 250px;"
          v-model="queryParams.channelId"
          :options="channelOptions"
          :show-count="true"
          placeholder="请选择订单归属渠道"
          noResultsText="暂无数据"
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单归属业务员" prop="businessUserId">
        <SelectBusinessUser
          style="width: 250px;"
          :defaultValue.sync="queryParams.businessUserId"
          :channelId="queryParams.channelId"
          :disabled="!queryParams.channelId"
          @change="handleQuery"
          placeholder="请先选择渠道,再选择归属业务员"
        />
      </el-form-item>

      <el-form-item label="开单日期">
        <el-date-picker
          v-model="createTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          :default-time="['00:00:00', '23:59:59']"
          @change="handleQuery"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb-8">
      <el-col :span="1.5">
        <DownloadExcel
          :fields="getTableFields('list')"
          :name="getDownloadTitle('list')"
          :fetch="exportList">
          <el-button type="primary" plain size="mini">订单导出</el-button>
        </DownloadExcel>
      </el-col>
      <el-col :span="1.5">
        <DownloadExcel
          :fields="getTableFields('detail')"
          :name="getDownloadTitle('detail')"
          :fetch="exportDetail">
          <el-button type="primary" plain size="mini">服务项目明细导出</el-button>
        </DownloadExcel>
      </el-col>
    </el-row>

    <el-table
      :data="tableList"
      v-loading="loading"
      style="width: 100%; margin-top: 20px"
      border
    >
      <el-table-column label="订单编号" align="center" width="210" fixed="left">
        <template slot-scope="{ row }">
          <el-link type="primary" @click="openDetails(row)">{{
            row.orderNo
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" align="center" width="160">
        <template slot-scope="{ row }">
          <div class="disFlxAC" style="justify-content: center">
            <dict-tag :options="dict.type.order_status" :value="row.status" />
            <div
              v-if="getMedicationStatusTitle(row)"
              class="ml-10"
              :style="{ color: getMedicationStatusTitle(row).color }"
            >
              ({{ getMedicationStatusTitle(row).title }})
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="开单时间"
        prop="createTime"
        align="center"
        width="180px"
      ></el-table-column>

      <el-table-column label="处方类型" align="center" width="180px">
        <template slot-scope="{ row }">
          <dict-tag
            v-if="row.parescriptOrder"
            :options="dict.type.tcm_prescript_type"
            :value="row.parescriptOrder.prescriptionType"
          />
        </template>
      </el-table-column>

      <el-table-column label="消费人信息" align="center" width="150px">
        <template slot-scope="{ row }">
          <template v-if="row.parescriptOrder && row.parescriptOrder.patientName">
            <div>
              <span>{{ row.parescriptOrder.patientName}}<span class="px-2">/</span></span>
              <span>{{ row.parescriptOrder.patientSex === 1 ? "女" : "男"}}<span class="px-2">/</span></span>
              <span>{{ row.parescriptOrder.patientAge }}岁</span>
            </div>
            <div>{{ row.parescriptOrder.patientPhone }}</div>
          </template>
          <template v-else>
            <div>{{ row.username }}</div>
            <div>{{ row.userphone }}</div>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        label="开单申请人"
        prop="sponsor"
        align="center"
        width="120px"
      ></el-table-column>
      <el-table-column
        label="申请人所属机构"
        prop="companyName"
        align="center"
        width="200"
      ></el-table-column>
      <el-table-column
        label="服务所属机构"
        prop="checkAgencyName"
        align="center"
        width="200"
      ></el-table-column>
      <el-table-column label="物流信息" width="200">
        <template slot-scope="{ row }">
          <div v-if="row.mailingInfo" class="fz-12">
            <div>{{ getLogisticInfoTitle(row) }}</div>
            <div v-if="row.mailingInfo.expressNumber">
              <span class="pr-5">{{ row.mailingInfo.expressBrand }}</span>
              <span>( {{ row.mailingInfo.expressNumber }} )</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单归属渠道" width="200" prop="channelName" align="center" />
      <el-table-column label="订单归属业务员" width="200" prop="businessUserName" align="center" />


      <el-table-column label="订单金额" align="center">
        <template slot-scope="{ row }">
          <div>￥{{ order_dingdanjinge(row) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="实付金额" align="center" width="150px">
        <template slot-scope="{ row }">
          <div v-if="order_shifujinge(row)">
            <div>￥{{ order_shifujinge(row) }}</div>
            <div class="fz-12 colorRED">{{ order_tuikuanjinge(row) }}</div>
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="180px" fixed="right">
        <template slot-scope="{ row }">
           <el-button size="mini" type="text" icon="el-icon-document" @click="openDetails(row)">
            订单详情
          </el-button>

          <el-button
            v-if="whetherSettle(row) && hasPermiAnd(['order:inspection:whetherSettle'])"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="openSettle(row)"
            >立即核销</el-button
          >
          <el-button
            v-if="nonPayment(row) && hasPermiAnd(['order:inspection:nonPayment'])"
            size="mini"
            type="text"
            icon="el-icon-money"
            @click="openOrderPlay(row)"
            >立即收款</el-button
          >
          <el-button
            v-if="showSettlement(row) && hasPermiAnd(['order:inspection:settlement'])"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="$router.push(`/order/resultdetails/index/${row.id}`)"
            >结算汇总</el-button
          >
          <el-button
            v-if="whetherConsignment(row) && hasPermiAnd(['order:inspection:whetherConsignment'])"
            size="mini"
            type="text"
            icon="el-icon-truck"
            @click="openLogistics(row.id, row.mailingInfo.id)"
            >立即发货</el-button
          >
          <el-button
            v-if="showCancelOrder(row) && hasPermiAnd(['order:inspection:showCancelOrder'])"
            size="mini"
            type="text"
            icon="el-icon-document-delete"
            @click="cancelOrder(row)"
            >取消订单</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <OrderPlay ref="OrderPlay" @refresh="getList" />
    <Logistics ref="Logistics" @refresh="getList" />
    <WriteOff ref="WriteOff" @refresh="getList" />
    <CancelOrder ref="CancelOrder" @refresh="getList" />
  </div>
</template>

<script>
import { getCheckOrderList } from "@/api/service";
import { numSub } from '@/utils/big/calculate.js'
import OrderPlay from '../components/orderPlay.vue'
import Logistics from '../components/logistics.vue';
import WriteOff from '../components/writeOff.vue'
import CancelOrder from '../components/cancelOrder.vue'
import SelectCompany from "@/components/SelectCompany";
import { parseTime } from '@/utils/ruoyi'
import { getPickerShortcuts } from '@/utils'
import { whetherSettle, nonPayment, showSettlement, whetherConsignment, showCancelOrder, getMedicationStatusTitle, getLogisticInfoTitle, order_dingdanjinge, order_shifujinge, order_tuikuanjinge, getDownloadTitle, getTableFields, recombineData } from '../components/mixin.js'
import DownloadExcel  from 'vue-json-excel'
import { treeselect } from "@/api/channel/channel";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import SelectBusinessUser from "@/views/system/user/selectBusinessUser";
import { hasPermiAnd } from '@/plugins/auth'

export default {
  name: 'Inspection',
  dicts: ["order_status", "tcm_prescript_type", "medication_status", "order_source"],
  components: {
    OrderPlay,
    Logistics,
    WriteOff,
    SelectCompany,
    Treeselect,
    CancelOrder,
    DownloadExcel,
    SelectBusinessUser
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      pickerOptions: {
        shortcuts: getPickerShortcuts()
      },
      createTime: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchValue: "",
        status: "",
        checkAgency: "", // 服务机构
        companyId: "", // 申请机构
        createTimegt: "", // 开始时间
        createTimelt: "", // 结束时间
        medicationStatus: undefined, // 取药状态 -1无 0未取药  1部分取药 2已取药
        orderSource: undefined,
        prescriptionType: undefined,
        channelId: undefined,
        businessUserId: undefined
      },
      tableList: [],
      // 渠道树选项
      channelOptions: [],
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  activated() {
    this.getList();
  },
  methods: {
    numSub,
    whetherSettle,
    nonPayment,
    showSettlement,
    whetherConsignment,
    showCancelOrder,
    getMedicationStatusTitle,
    getLogisticInfoTitle,
    order_dingdanjinge,
    order_shifujinge,
    order_tuikuanjinge,
    getDownloadTitle,
    getTableFields,
    hasPermiAnd,
    getList() {
      this.queryParams.createTimegt = this.createTime && this.createTime.length ? this.createTime[0] : "";
      this.queryParams.createTimelt = this.createTime && this.createTime.length ? this.createTime[1] : "";
      getCheckOrderList(this.queryParams).then((response) => {
        this.tableList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询渠道下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.channelOptions = response.data;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.createTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 跳转订单详情
    openDetails(row) {
      this.$router.push(`/order/inspectionDetails/index?id=${row.id}&childOrderId=${row.childOrderId}`);
    },
    // 打开核销弹窗
    openSettle(row) {
      this.$refs.WriteOff.openModal(row);
    },
    // 去收款
    openOrderPlay(info) {
      this.$refs.OrderPlay.show(info)
    },
    // 去发货
    openLogistics(orderId, id) {
      this.$refs.Logistics.openModal(orderId, id)
    },
    // 取消订单
    cancelOrder(row) {
      this.$refs.CancelOrder.openModal(row)
    },
    handleExport() {
      this.download("check/order/export", this.queryParams, `服务订单_${parseTime(new Date(), '{y}-{m}-{d}')}.xlsx`);
    },
    handleItemExport() {
      this.download("check/item/export", this.queryParams, `服务项目明细_${parseTime(new Date(), '{y}-{m}-{d}')}.xlsx`);
    },
    exportList() {
      return recombineData('list', this)
    },
    exportDetail() {
      return recombineData('detail', this)
    }
  },
};
</script>
<style scoped>
.cell>button:nth-child(3){
  margin-left: 0 !important;
}
</style>
